<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2022/12/22
 * Time: 20:05
 */

namespace App\Http\Controllers;


use App\Channel\Russia;
use App\Channel\Wyvn;
use App\Constant;
use App\Events\RechargeComplete;
use App\Models\BalanceLogModel;
use App\Models\PaylogModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class NotifyController extends Controller
{
    public function russia(Request $request){
        Log::error('ru回调：' . json_encode($request->input()));
        
        $result = $request->input();
        
        $signData = [
            'sysOrderId' => $result['sysOrderId'],
            'merchantOrderId' => $result['merchantOrderId'],
            'status' => $result['status'],
            'amount' => $result['amount'],
            'fee' => $result['fee'],
            'realAmount' => $result['realAmount'],
            'successTime' => $result['successTime'],
            'createTime' => $result['createTime'],
        ];
        //$apikey = 'b840cebc620145a58b2dbb6ea1b035a0';
        $apikey = '1';
        $mysign = $this->mdsign($apikey,$signData);
        
        if('3.0.64.107' == $this->get_client_ip() || '54.251.182.101' == $this->get_client_ip()){
            if($mysign != $result['sign']) {
            Log::error('签名错误');
            Log::error('签名错误'.'签名结果'.$mysign);
            return;
            }
        }else {
            Log::error('回调IP错误');
            return;
        }
        

        $paylog_model = PaylogModel::where('trade_no', $result['merchantOrderId'])->first();
        if($paylog_model->status == Constant::YES) {
            Log::error('订单已经支付');
            return;
        }

        DB::beginTransaction();
        $paylog_model->fill([
            'status' => Constant::YES,
            'transaction_no' => $result['merchantOrderId']
        ])->save();

        if($paylog_model->relate_type == Constant::PAYLOG_TYPE_RECHARGE) {
            // 更新充值记录
            $wallet_model = $paylog_model->relate;
            $wallet_model->approval = Constant::YES;
            //$wallet_model->payment_method = '51pay';
            //$wallet_model->payment_details = json_encode($result);
            $wallet_model->offline_payment = Constant::YES;
            $wallet_model->save();

            $user_model = $wallet_model->user;
            $balance_log_model = BalanceLogModel::create([
                'user_id' => $user_model->id,
                'type' => Constant::BALANCE_LOG_TYPE_RECHARGE,
                'value_before' => $user_model->balance,
                'value' => $wallet_model->amount,
                'description' => "Recharge",
                'trade_id' => $wallet_model->id,
            ]);

            // 更新关联用户
            $user_model->balance = $user_model->balance + $wallet_model->amount;
            $user_model->save();
        } elseif($paylog_model->relate_type == Constant::PAYLOG_TYPE_DEPOSIT) {
            // 更新充值记录
            $wallet_model = $paylog_model->relate;
            $wallet_model->approval = Constant::YES;
            //$wallet_model->payment_method = '51pay';
            //$wallet_model->payment_details = json_encode($result);
            $wallet_model->offline_payment = Constant::YES;
            $wallet_model->save();

            $user_model = $wallet_model->user;

            // 更新关联用户
            $user_model->deposit = $user_model->deposit + $wallet_model->amount;
            $user_model->save();
        }

        DB::commit();


        if($paylog_model->relate_type == Constant::PAYLOG_TYPE_RECHARGE) {
            event(new RechargeComplete($paylog_model));
        }


        return response()->json(['code' => 1, 'success' => true, 'message' => '成功']);
    }
    
    public function wyvn(Request $request){
        Log::error('wy回调：' . json_encode($request->post()));
        $resultjson = $request->post();
        $result = json_decode($resultjson['data'],true);
        
        $apiKey = 'msmchcpyina2hs524hli8t92kboowtt1';
        $amount = $result['amount'];
        $orderId = $result['orderid'];
        $mysign = md5($apiKey.$orderId.$amount);
        Log::error('wyvn加密结果' . $mysign);
        echo('success');
        if($result['sign'] != $mysign){
            Log::error('wyvn加密签名参数' . $apiKey.$orderId.$amount);
            Log::error('验签失败！！');
            return;
        }
        if($resultjson['code'] != 1) {
            Log::error('付款状态：失败');
            return;
        }

        $paylog_model = PaylogModel::where('trade_no', $orderId)->first();
        if($paylog_model->status == Constant::YES) {
            Log::error('流水已支付');
            return;
        }

        DB::beginTransaction();
        $paylog_model->fill([
            'status' => Constant::YES,
            'transaction_no' => $result['orderNumber']
        ])->save();

        if($paylog_model->relate_type == Constant::PAYLOG_TYPE_RECHARGE) {
            // 更新充值记录
            $wallet_model = $paylog_model->relate;
            $wallet_model->approval = Constant::YES;
            $wallet_model->payment_method = 'VN';
            //$wallet_model->payment_details = json_encode($result);
            $wallet_model->offline_payment = Constant::YES;
            $wallet_model->save();
            // 更新关联用户
            $user_model = $wallet_model->user;
            $user_model->balance = $user_model->balance + $wallet_model->amount;
            $user_model->save();
        } elseif($paylog_model->relate_type == Constant::PAYLOG_TYPE_DEPOSIT) {
            // 更新充值记录
            $wallet_model = $paylog_model->relate;
            $wallet_model->approval = Constant::YES;
            //$wallet_model->payment_method = '51pay';
            //$wallet_model->payment_details = json_encode($result);
            $wallet_model->offline_payment = Constant::YES;
            $wallet_model->save();

            $user_model = $wallet_model->user;

            // 更新关联用户
            $user_model->deposit = $user_model->deposit + $wallet_model->amount;
            $user_model->save();
        }

        DB::commit();
        
         if($paylog_model->relate_type == Constant::PAYLOG_TYPE_RECHARGE) {
            event(new RechargeComplete($paylog_model));
        }

        return response()->json(['code' => 1, 'success' => true, 'message' => '成功']);
    }
    
    public function mdsign($apikey,$native){
        ksort($native);
        $md5str = "";
        foreach ($native as $key => $val) {
            $md5str = $md5str . $key . "=" . $val . "&";
        }
        $md5str = $md5str.'key='.$apikey;
        Log::error('签名源字符串'.$md5str);
        $sign = hash_hmac('sha256', $md5str, $apikey);
        return $sign;
    }
    
    function get_client_ip($type = 0) {
    $type       =  $type ? 1 : 0;
    static $ip  =   NULL;
    if ($ip !== NULL) return $ip[$type];
    if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $arr    =   explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
        $pos    =   array_search('unknown',$arr);
        if(false !== $pos) unset($arr[$pos]);
        $ip     =   trim($arr[0]);
    }elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
        $ip     =   $_SERVER['HTTP_CLIENT_IP'];
    }elseif (isset($_SERVER['REMOTE_ADDR'])) {
        $ip     =   $_SERVER['REMOTE_ADDR'];
    }
    // IP地址合法验证
    $long = sprintf("%u",ip2long($ip));
    $ip   = $long ? array($ip, $long) : array('0.0.0.0', 0);
    return $ip[$type];
}
}